package com.masterclient.app.businessmodule.minemodule.cash;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.eoner.uikit.adapter.simplepage.SimplePagerAdapter;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.R;
import com.masterclient.app.base.CashCommonDialog;
import com.masterclient.app.base.CashToastDialog;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.minemodule.withdraw.GainCashActivity;
import com.masterclient.app.businessmodule.minemodule.cash.fragment.BalanceCashFragment;
import com.masterclient.app.businessmodule.minemodule.cash.fragment.BalanceGainFragment;
import com.masterclient.app.businessmodule.minemodule.cash.fragment.BalanceOrderFragment;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.businessmodule.minemodule.cash.bean.BalanceGainBean;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.widget.EnhanceTabLayout;
import com.masterclient.app.widget.RemindDialog;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：sean
 * 创建时间：2017/10/11 14:47
 * 功能说明：
 */
@Route(path = FCRouterPath.MINE_INCOME_PATH)
public class CashAccountActivity extends FCBusinessActivity {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_rule)
    LinearLayout rlRule;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_red_pack_num)
    TextView tvRedPackNum;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.tabLayout)
    EnhanceTabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_tixian)
    TextView tvTixian;
    @BindView(R.id.tv_freez)
    TextView tvFreez;
    @BindView(R.id.status_bar)
    View statusBar;
    @BindView(R.id.upload_ids)
    View upload_ids;
    @BindView(R.id.id_card_layout)
    View id_card_layout;
    @BindView(R.id.head_rl)
    RelativeLayout headRl;
    @BindView(R.id.ids_message)
    TextView ids_message;

    private List<Fragment> fragments;

    private BalanceGainFragment balanceGainFragment;//获取
    private BalanceOrderFragment balanceOrderFragment;//支出
    private BalanceCashFragment balanceCashFragment;//提现

    private SimplePagerAdapter cashPagerAdapter;
    String amount = "0.00";
    String url;
    String sh_is_bind_mobile;

    String action = "refresh";
    private String delete_status,descs;

    private BroadcastReceiver mBoradcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action)) {
                balanceGainFragment.refreshList();
                balanceCashFragment.refreshList();
            }
        }
    };

    private boolean canWithdraw = true;


    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_cash;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setVisibility(View.GONE);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {

        ImmersionBar.with(this).statusBarDarkFont(true).statusBarView(statusBar).transparentStatusBar().init();

        Utils.setDin(tvRedPackNum,this);
        fragments = new ArrayList<>();
        balanceGainFragment = new BalanceGainFragment();
        balanceOrderFragment = new BalanceOrderFragment();
        balanceCashFragment = new BalanceCashFragment();

        balanceGainFragment.setDataListerner(new BalanceGainFragment.DataListerner() {
            @Override
            public void setData(BalanceGainBean.DataBean dataBean,BalanceGainBean.DataBean.ShBalanceInfoBean balanceInfoBean) {
                amount = balanceInfoBean.getSh_user_balance();
                delete_status = balanceInfoBean.getSh_delete_status();
                descs = balanceInfoBean.getSh_descs();
                tvRedPackNum.setText(balanceInfoBean.getSh_user_balance());
                tvFreez.setText("（冻结："+balanceInfoBean.getSh_freeze_amount()+"元）");

                if(Double.valueOf(balanceInfoBean.getSh_user_balance())<=0 | !dataBean.isSh_cash_withdrawal_status()){//
                    //tvTixian.setBackgroundColor(0xFFE8E8EF);
                    tvTixian.setBackgroundResource(R.drawable.shape_round_f0f2f5);
                    if(Double.valueOf(balanceInfoBean.getSh_user_balance())<=0){
                        tvTixian.setText("提现");
                    }else{
                        tvTixian.setText(dataBean.getSh_cash_withdrawal_message());
                    }
                    tvTixian.setTextColor(0xff525866);
                    //tvTixian.setClickable(false);
                    canWithdraw = false;
                }
            }

            @Override
            public void setIntro(String surl,String sh_is_bind_mobile) {
                url = surl;
                CashAccountActivity.this.sh_is_bind_mobile = sh_is_bind_mobile;
            }
        });

        fragments.add(balanceGainFragment);
        fragments.add(balanceOrderFragment);
        fragments.add(balanceCashFragment);

        String [] sTitle = {"获取明细","支出明细","提现记录"};
        cashPagerAdapter = new SimplePagerAdapter(getSupportFragmentManager(),fragments);
        for(int i = 0;i < sTitle.length;i ++){
            tabLayout.addTab(sTitle[i],i == 0);
        }
        viewPager.setAdapter(cashPagerAdapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout.getTabLayout()));
        tabLayout.setupWithViewPager(viewPager);

        IntentFilter filter = new IntentFilter();
        filter.addAction(action);//为BroadcastReceiver指定一个action，即要监听的消息名字
        registerReceiver(mBoradcastReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")){
            id_card_layout.setVisibility(View.VISIBLE);
            ids_message.setText(UserDataManager.getInstance().getIdCardMessage());
        }else{
            id_card_layout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBoradcastReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 103:
                viewPager.setCurrentItem(2);
                viewPager.postDelayed(()->{
                    balanceCashFragment.refreshList();
                },1000);

                CashToastDialog cashToastDialog = new CashToastDialog(mContext);
                cashToastDialog.show();

                break;
            case 104:
                Intent intent = new Intent(mContext, GainCashActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("amount",amount);
                bundle.putString("url",url);
                intent.putExtras(bundle);
                startActivityForResult(intent,103);
                break;
        }
    }

    CashCommonDialog cashCommonDialog;
    @OnClick({R.id.rl_back,R.id.tv_tixian,R.id.rl_rule,R.id.upload_ids})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_tixian:

                if(!canWithdraw){
                    return;
                }
                if ("0".equals(delete_status)){
                    new RemindDialog(this, descs, "确定").show();
                    return;
                }
                if("1".equals(sh_is_bind_mobile)) {
                    if (!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")) {
                        if (cashCommonDialog == null) {
                            cashCommonDialog = new CashCommonDialog(mContext, "为保证您的资金账户安全，请上传您本人身份证用于账户安全保护", "取消", "去上传");
                        }
                        cashCommonDialog.setOnChooseListerner(new CashCommonDialog.OnChooseListerner() {
                            @Override
                            public void cancel() {
                                cashCommonDialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                cashCommonDialog.dismiss();

                                ARouter.getInstance().build(FCRouterPath.SETTING_AUTH_PATH)
                                        .withInt("source",1)
                                        .navigation(CashAccountActivity.this,new FCBaseIntercept());
                            }
                        });
                        cashCommonDialog.show();
                    }else{
                        Intent intent = new Intent(mContext, GainCashActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("amount", amount);
                        bundle.putString("url", url);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 103);
                    }
                }else {
                    ConfirmDialog confirmDialog = new ConfirmDialog(mContext,"为了您的资金安全，请先绑定手机号","暂不绑定","去绑定");
                    confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                        @Override
                        public void cancel() {
                            confirmDialog.dismiss();
                        }
                        @Override
                        public void confirm() {
                            confirmDialog.dismiss();
                            startActivityForResult(new Intent(mContext, BinderMobileActivity.class),88);
                        }
                    });
                    confirmDialog.show();
                }

                break;
            case R.id.rl_rule:
                startActivitry(BridgeActivity.class,new String[][]{{"url",url},{"title","钱包账户说明"}});
                break;
            case R.id.upload_ids:

                ARouter.getInstance().build(FCRouterPath.SETTING_AUTH_PATH)
                        .withInt("source",1)
                        .navigation(CashAccountActivity.this,new FCBaseIntercept());
                break;
        }
    }
}
